<template>
  <div class="qq-lemon-imui">
    <lemon-imui class="lemon-slot" :user="UserData" marginRight="240px" hide-message-name hide-message-time ref="IMUI"
      :height="height" :hide-file-size="true" @pull-messages="handlePullMessages" @change-contact="handleChangeContact"
      @send="handleSend" @change-menu="handleChangeMenu" @message-click="handleMessageClick"
      @changeNearContact="changeNearContact" @menu-avatar-click="handleMenuAvatarClick" :contextmenu="contextmenu"
      :contact-contextmenu="contactContextmenu" :limit="9" @on-exceed="handleExceed" @editorPaste="editorPaste">
      <template #msg-image="url">
        <el-image style="display: block" :src="url" :preview-src-list="[url]" @click="checkImage" />
      </template>
      <div slot="sidebar-message-fixedtop">
        <Search @select="handleSelect" />
      </div>
      <template #cover>
        <div class="slot-btn">
          <el-button v-show="type == 1" class="close" type="danger" icon="el-icon-close" size="mini" style="
<<<<<<< HEAD
                      background: none;
                      border: none;
                      color: #bbb;
                      margin-left: calc(100% - 50px);
                    " @click="handleClose()"></el-button>
=======
                                                        background: none;
                                                        border: none;
                                                        color: #bbb;
                                                        margin-left: calc(100% - 50px);
                                                      " @click="handleClose()"></el-button>
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
        </div>
      </template>
      <template #no-reminder-icon>
        <div>
          <i class="el-icon-close-notification" style="color: #bbb"></i>
        </div>
      </template>
      <template #message-title="contact">
        <span v-if="isEdit == false">
          <span @click="edit(contact)">{{ contact.displayName
          }}<span v-if="numberOnline">({{ numberOnline }})</span>
          </span>
        </span>
        <input type="text" v-if="isEdit == true" v-model="contact.displayName" class="editInput"
          @blur="saveGroupName(contact)" ref="inputRef" maxlength="50" />
        <span class="slot-btn" :style="drawerVisible ? 'margin-right:0px' : 'margin-right:0px'">
<<<<<<< HEAD
          <small class="more" style="height: 10px; line-height: 2px; color: #bbb" @click="changeDrawer(contact)"><i
              class="el-icon-more"></i></small>
=======
          <small class="more" style="height: 10px; line-height: 2px; color: #bbb" @click="changeDrawer(contact)">. .
            .</small>
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
          <el-button v-show="type == 1" class="close" type="danger" icon="el-icon-close" size="mini"
            style="background: none; border: none; color: #bbb; margin-left: 0" @click="handleClose()"></el-button>
        </span>
      </template>
    </lemon-imui>
    <div class="user-info-model" @click="model" v-show="userInfo === true"
      :style="{ left: offsetX + 'px', top: offsetY + 'px' }">
      <div class="user-info">
        <div class="user-info-header">
          <div class="user-info-avatar">
            {{
              currentUserInfo.realName && currentUserInfo.realName.substr(-2)
            }}
          </div>
          <div style="display: flex; flex-direction: column; padding: 10px">
            <span class="user-info-text">{{ currentUserInfo.realName }}</span>
            <span class="user-info-account">账号：{{ currentUserInfo.username }}</span>
          </div>
        </div>
        <div class="user-info-footer">
          <div class="user-info-item">
            <span class="user-info-label">大赢家id:</span>
            <span class="user-info-value">{{ currentUserInfo.dyjCode }}</span>
          </div>
          <div class="user-info-item">
            <span class="user-info-label">部门:</span>
            <span class="user-info-value">{{
              currentUserInfo.departmentName
            }}</span>
          </div>
          <div class="user-info-item">
            <span class="user-info-label">手机号:</span>
            <span class="user-info-value">{{ currentUserInfo.mobile }}</span>
          </div>
          <div class="user-info-item">
            <span class="user-info-label">邮箱:</span>
            <span class="user-info-value"></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Contacts from "./Contact.vue";
import Group from "./Group.vue";
import Sidebar from "./Sidebar.vue";
import Search from "./Search.vue";
import debounce from "../utils/debounce";
import { saveAs } from "file-saver";
import { createLogger } from "vuex";
import { urlConfig,env } from "../utils/urlConfig";
import { Collapse, Loading } from "element-ui";
import Stomp from "stompjs";
import { GetMessage } from "@/utils/browser";
import moment from "moment";
import { log } from "@/api/login.js"

const cachePageInfo = new Map();
const getTime = () => {
  return new Date().getTime();
};
const uploadWs = {};
export default {
  name: "QqImui",
  components: {},
  props: ["name", "id", "type"],
  provide() {
    return {
      IMUI: this.$refs.IMUI,
    };
  },
  data() {
    return {
      imageType: "",
      wrapperElem: null,
      unreadItem: {},
      height: "640px",
      is_group: 1,
      mids: [],
      displayName: "",
      oldName: "",
      isEdit: false,
      moment: moment,
      currentWsGroupId: null,
      kernel: "",
      WebSocket: "",
      lockReconnect: false, //是否真正建立连接
      timeout: 28 * 1000, //30秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      UserData: {},
      selectChange: false,
      groupId: "",
      username: "",
      currentContactObj: {},
      currentUserInfo: {},
      userInfo: false,
      value: "",
      offsetX: 0,
      offsetY: 0,
      numberOnline: "",
      drawerVisible: false,
      client: null,
      clientRetraction: null,
      clientRead: null,
      clientTreenode: null,
      clientUser: null,
      url: "",
      all: [],
      unreadMessage: 0,
      currentUnread: 0,
      // showContainer: false,
      toUser: "",
      updateUnread: "",
      copyText: "",
      websocketParams: "",
      contactContextmenu: [
        {
          icon: "el-icon-upload2",
          text: "置顶聊天",
          click: async (e, instance, hide) => {
            const { IMUI, contact } = instance;
            const fromUserAccount = this.name;
            const toUserAccount = contact.id;
            const status = 1;
            const accountId = this.id;
            if (contact.type == 1) {
              const params = `${fromUserAccount}/${toUserAccount}/${status}`;
              const result = await this.$API.admins.topping(params);
            } else if (contact.type == 2) {
              const groupId = contact.id;
              const username = this.name;
              const params = `${groupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.groupToppingAccount(params);
            } else if (contact.type == 3) {
              const userGroupId = contact.id;
              const username = this.name;
              const params = `${userGroupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.userGroupToppingAccount(
                params
              );
            }
            hide();
          },
          visible: (instance) => {
            console.log("tag1111111w", instance);
            return !!instance.contact.toppingTime === false;
          },
        },
        {
          icon: "el-icon-download",
          text: "取消置顶",
          click: async (e, instance, hide) => {
            const { IMUI, contact } = instance;
            const fromUserAccount = this.name;
            const toUserAccount = contact.id;
            const status = 0;
            const accountId = this.id;
            if (contact.type == 1) {
              const params = `${fromUserAccount}/${toUserAccount}/${status}`;
              const result = await this.$API.admins.topping(params);
            } else if (contact.type == 2) {
              const groupId = contact.id;
              const username = this.name;
              const params = `${groupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.groupToppingAccount(params);
            } else {
              const userGroupId = contact.id;
              const username = this.name;
              const params = `${userGroupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.userGroupToppingAccount(
                params
              );
            }
            hide();
          },
          visible: (instance) => {
            return !!instance.contact.toppingTime;
          },
        },
        {
          icon: "el-icon-bell",
          text: "消息免打扰",
          click: async (e, instance, hide) => {
            const { IMUI, contact } = instance;
            const fromUserAccount = this.name;
            const toUserAccount = contact.id;
            const status = 1;
            const accountId = this.id;
            if (contact.type === 1) {
              const params = `${toUserAccount}/${fromUserAccount}/${status}`;
              const result = await this.$API.admins.personNoReminder(params);
            } else if (contact.type == 2) {
              const groupId = contact.id;
              const username = this.name;
              const params = `${groupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.groupNoReminder(params);
            } else {
              const userGroupId = contact.id;
              const username = this.name;
              const params = `${userGroupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.userGroupNoReminder(params);
            }
            hide();
          },
          visible: (instance) => {
            return !!instance.contact.noReminder == false;
          },
        },
        {
          icon: "el-icon-close-notification",
          text: "取消免打扰",
          click: async (e, instance, hide) => {
            const { IMUI, contact } = instance;
            const fromUserAccount = this.name;
            const toUserAccount = contact.id;
            const status = 0;
            const accountId = this.id;
            if (contact.type === 1) {
              const params = `${toUserAccount}/${fromUserAccount}/${status}`;
              const result = await this.$API.admins.personNoReminder(params);
            } else if (contact.type == 2) {
              const groupId = contact.id;
              const username = this.name;
              const params = `${groupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.groupNoReminder(params);
            } else {
              const userGroupId = contact.id;
              const username = this.name;
              const params = `${userGroupId}/${accountId}/${username}/${status}`;
              const result = await this.$API.admins.userGroupNoReminder(params);
            }
            hide();
          },
          visible: (instance) => {
            return instance.contact.noReminder == true;
          },
        },
        {
          color: "red",
          icon: "el-icon-delete",
          text: "删除聊天",
          click: async (e, instance, hide) => {
            const { IMUI, contact } = instance;
            if (contact.type == 1) {
              const chatResult = await this.$API.admins.removeChat(
                this.name,
                contact.id
              );
              const result = await this.$API.admins.emptyChat(
                this.name,
                contact.id
              );
              if (chatResult.code == 200) {
                IMUI.removeContact(contact.id);
              }
            } else if (contact.type == 2) {
              const groupChatResult = await this.$API.admins.removeGroupChat(
                contact.id,
                this.id,
                this.name
              );
              const result = await this.$API.admins.emptyGroupChat(
                contact.id,
                this.id,
                this.name
              );
              if (groupChatResult.code == 200) {
                IMUI.removeContact(contact.id);
              }
            } else {
              const userGroupChatResult =
                await this.$API.admins.removeUserGroupChat(
                  contact.id,
                  this.id,
                  this.name
                );
              const result = await this.$API.admins.emptyUserGroupChat(
                contact.id,
                this.id,
                this.name
              );
              if (userGroupChatResult.code == 200) {
                IMUI.removeContact(contact.id);
              }
            }
            hide();
          },
        },
      ],
      contextmenu: [
        {
          text: "撤回消息",
          click: async (e, instance, hide) => {
            const { IMUI, message } = instance;
            const type = this.$refs.IMUI.getCurrentContact().type;
            const newTime = new Date().getTime();
            if (type == 1) {
              const personRecallMessage = await this.$API.admins.recallMessage(
                message.id,
                parseInt(newTime / 1000)
              );
            } else if (type == 2) {
              const groupMessage = await this.$API.admins.groupRecallMessage({
                groupMessageId: message.id,
                retractionTime: moment(new Date()).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
              });
            } else {
              const userGroupMessage =
                await this.$API.admins.userGroupRecallMessage({
                  groupMessageId: message.id,
                  retractionTime: moment(new Date()).format(
                    "YYYY-MM-DD HH:mm:ss"
                  ),
                });
            }
            const data = {
              id: message.id,
              type: "event",
              content: (
                <div>
                  <span>你撤回了一条消息 </span>
                </div>
              ),
              edit: (
                <span
                  v-show={message.type == "text"}
                  style="color:#333;cursor:pointer"
                  content={message.content}
                  on-click={(e) => {
                    IMUI.setEditorValue(e.target.getAttribute("content"));
                  }}
                >
                  重新编辑
                </span>
              ),
              toContactId: message.toContactId,
              sendTime: getTime(),
            };
            IMUI.updateMessage(data);
            hide();
          },
          visible: (instance) => {
            return (
              instance.message.fromUser.id == this.name &&
              getTime() - instance.message.sendTime < 120000
            );
          },
        },
        {
          text: "复制",
          click: (e, instance, hide) => {
            var input = document.createElement("input"); // 直接构建input
            input.value = instance.message.content; // 设置内容
            this.copyText = input.value;
            console.log(input.value);
            document.body.appendChild(input); // 添加临时实例
            input.select(); // 选择实例内容
            document.execCommand("Copy"); // 执行复制
            document.body.removeChild(input); // 删除临时实例
            hide();
          },

          visible: (instance) => {
            return instance.message.type == "text";
          },
        },
      ],
<<<<<<< HEAD
      logItem: {
        environmentId: "",
        systemId: 2,
        module: "",
        serviceId: 13,
        url: "/:id/:name/:type"
      }
=======
      // pageItem: {
      //   environmentId: "",
      //   systemId: 1,
      //   module: "",
      //   serviceId: 1,
      //   url: "/:id/:name/:type"
      // }
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
    };
  },
  components: {
    Search,
    Sidebar,
    Group,
  },
  computed: {},
  watch: {},
  created() {
    this.connect(); // stomp连接mq
    this.connectRetraction();
    this.connectRead();
    this.connectTreenode();
    this.connectUser();
    this.handleLog()
  },
  mounted() {
    this.getLogin();
    const IMUI = this.$refs.IMUI;
    this.getAccount(IMUI);
    
  },
  methods: {
<<<<<<< HEAD
    // 监控系统页面访问日志
    handleLog(){
      console.log('tag', env)
      if(env == 'dev'){
        this.logItem.environmentId = 1
      }else if(env == 'test'){
        this.logItem.environmentId = 2
      }else if(env == 'prod'){
        this.logItem.environmentId = 4
      }

      log(this.logItem).then(res=>{
        console.log('tag',res)
      })
    },
=======
    // 页面访问日志
    // handleLog() {
    //   // this.logItem.url = window.location.hash.substr(1)
    //   console.log('tag1111ppp',env)
    //   if(env == 'dev'){
    //     this.pageItem.environmentId = 1
    //   }else if(env == 'test'){
    //     this.pageItem.environmentId = 2
    //   }else if(env == 'prod'){
    //     this.pageItem.environmentId = 4
    //   }
    //   log(this.pageItem).then(res => {
    //     console.log('tag', res)
    //   })

    // },
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
    editorPaste(cb) {
      cb(this.copyText);
      this.copyText = "";
    },
    //下载图片
    checkImage() {
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        );
        let downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-download");
        wrapper[0].appendChild(downImg);
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.cusClickHandler();
        }
      });
    },
    cusClickHandler() {
      this.wrapperElem.addEventListener("click", this.hideCusBtn);
    },
    hideCusBtn(e) {
      let className = e.target.className;
      if (className === "el-icon-download") {
        let imgUrl = document.getElementsByClassName(
          "el-image-viewer__canvas"
        )[0].children[0].src;
        this.downloadImage(imgUrl, 3);
      }
    },
    async downloadImage(imgUrl, type) {
      let fileNameArray = imgUrl && imgUrl.split("/");
      //开启遮罩层
      let loadingInstance = Loading.service({
        lock: true, //lock的修改符--默认是false
        text: "正在下载文件，请耐心等待", //显示在加载图标下方的加载文案
        spinner: "el-icon-loading", //自定义加载图标类名
        background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
        target: document.querySelector("#futureTransferDialog"), //loadin覆盖的dom元素节点
      });

      let downloadFileName = undefined;
      if (fileNameArray.length == 1) {
        downloadFileName = fileNameArray[0];
      } else {
        downloadFileName = fileNameArray[fileNameArray.length - 1];
      }
      // 下载文件
      await this.$API.admins
        .fileDownload({ filename: downloadFileName, type })
        .then((response) => {
          //关闭遮罩层
          console.log("tag", response);
          loadingInstance.close();
          const blob = new Blob([response], { type: "" });
          saveAs(blob, imgUrl);
        })
        .catch((error) => {
          //关闭遮罩层
          loadingInstance.close();
          this.$message.error(error);
        });
    },
    //个人对话
    initWebsocket() {
      // http://192.168.80.109:12101/
      if (this.type == 1) {
        this.websocket = new WebSocket(
          `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${this.name}/`,
          "Authorization'4f52f26643d647b9b6a4e94c1147f9c2"
        );
      } else {
        this.websocket = new WebSocket(
          `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${this.name}/`,
          "Authorization'907d64edbed348879e988334c6343deb"
        );
      }

      this.websocket.onopen = this.onopen;

      this.websocket.onmessage = this.onmessage;

      this.websocket.onclose = this.onclose;

      this.websocket.onerror = this.onerror;

      let thatWebsocket = this.websocket;
      // window.setInterval(function () {
      //   //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
      //   let ping = { type: -1 };
      //   thatWebsocket.send(JSON.stringify(ping));
      // }, 5000);
    },
    //群聊对话
    initWebsocket1(params, id) {
      // type 2 默认群  type 3 自定义群
      // const group = type == 2 ?  'group':'userGroup'
      if (this.type == 1) {
        this.websocket1 = new WebSocket(
          `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${params}/`,
          "Authorization'4f52f26643d647b9b6a4e94c1147f9c2"
        );
      } else {
        this.websocket1 = new WebSocket(
          `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${params}/`,
          "Authorization'907d64edbed348879e988334c6343deb"
        );
      }

      this.currentWsGroupId = id;
      this.websocket1.onopen = this.onopen1;

      this.websocket1.onmessage = this.onmessage1;

      this.websocket1.onclose = this.onclose1;

      this.websocket1.onerror = this.onerror1;
      // window.setInterval(() => {
      //   //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
      //   let ping = { type: -1 };
      //   this.websocket1.send(JSON.stringify(ping));
      // }, 5000);
    },
    //上传图片限制
    handleExceed() {
      this.$message.error("一次最多只能上传9张");
    },
    //显示输入框时自动聚焦
    edit(contact) {
      if (contact.type == 3) {
        this.isEdit = true;
        this.$nextTick(() => {
          this.$refs.inputRef.focus();
        });
      }
    },
    //修改群名
    async saveGroupName(contact) {
      if (contact.displayName.length < 1) {
        this.$message.error("群名称不能为空！");
        this.isEdit = false;
        return false;
      }
      // 如果更改了名称，请求服务器，并通知所有群更改名称
      if (contact.displayName != this.oldName) {
        const { IMUI } = this.$refs;
        const result = await this.$API.admins
          .editUserGroupName({
            id: contact.id,
            name: contact.displayName,
            membership: this.numberOnline,
            updateUserGroupNameAccount: this.name,
            updateUserGroupNameRealName: IMUI.user.displayName,
          })
          .then((res) => {
            IMUI.updateContact({
              id: contact.id,
              displayName: contact.displayName,
            });
          });
        // IMUI.appendMessage(
        //   {
        //     id: this.id,
        //     type: "event",
        //     content: (
        //       <span>
        //         {IMUI.user.displayName} 修改了群名为 {contact.displayName}
        //       </span>
        //     ),
        //     toContactId: contact.id,
        //     sendTime: getTime(),
        //   },
        //   true
        // );
      }
      this.isEdit = false;
    },
    //监听mq
    onConnected(frame) {
      // data.body是接收到的数据
      this.client.subscribe(
        `/exchange/im-end.current/${this.name}`,
        async (data) => {
          let msg = data.body;
          const result = JSON.parse(msg).result;
          console.log(JSON.parse(msg));
          const result1 = JSON.parse(msg);
          const { IMUI } = this.$refs;
          result.forEach((item) => {
            if (item.type == 3 && item.lastMessageType == 5) {
              if (
                IMUI.currentContactId == item.groupId &&
                IMUI.currentMessages.length > 0 &&
                IMUI.currentMessages[IMUI.currentMessages.length - 1]
                  .content !== item.lastMessage
              ) {
                IMUI.appendMessage(
                  {
                    id: item.msgId,
                    type: "event",
                    content: item.lastMessage,
                    toContactId: item.groupId,
                    sendTime: item.lastMessageTime,
                  },
                  true
                );
                IMUI.updateContact({
                  id: item.id,
                  displayName: item.name,
                });
              }
            } else if (item.type == 1 && item.lastMessageType == 4) {
              this.$refs.IMUI.updateMessage({
                id: item.retractionMsgId,
                type: "event",
                content: item.lastMessage,
                toContactId: item.username,
                sendTime: new Date().getTime(),
                edit: (
                  <span
                    v-show={item.fromUserAccount == this.name}
                    style="color:#333;cursor:pointer"
                    content={item.retractionContent}
                    on-click={(e) => {
                      this.$refs.IMUI.setEditorValue(
                        e.target.getAttribute("content")
                      );
                    }}
                  >
                    重新编辑
                  </span>
                ),
              });
            } else if (item.type == 2 && item.lastMessageType == 4) {
              this.$refs.IMUI.updateMessage({
                id: item.retractionMsgId,
                type: "event",
                content: item.lastMessage,
                toContactId: item.username,
                sendTime: new Date().getTime(),
                edit: (
                  <span
                    v-show={item.fromUserAccount == this.name}
                    style="color:#333;cursor:pointer"
                    content={item.retractionContent}
                    on-click={(e) => {
                      this.$refs.IMUI.setEditorValue(
                        e.target.getAttribute("content")
                      );
                    }}
                  >
                    重新编辑
                  </span>
                ),
              });
            } else if (item.type == 3 && item.lastMessageType == 4) {
              this.$refs.IMUI.updateMessage({
                id: item.retractionMsgId,
                type: "event",
                content: item.lastMessage,
                toContactId: item.username,
                sendTime: new Date().getTime(),
                edit: (
                  <span
                    v-show={item.fromUserAccount == this.name}
                    style="color:#333;cursor:pointer"
                    content={item.retractionContent}
                    on-click={(e) => {
                      this.$refs.IMUI.setEditorValue(
                        e.target.getAttribute("content")
                      );
                    }}
                  >
                    重新编辑
                  </span>
                ),
              });
            }
            IMUI.appendContact({
              id: item["type"] == 1 ? item["username"] : item["groupId"],
              displayName:
                item["type"] === 1
                  ? item["realName"]
                  : item["type"] === 2
                    ? item["name"]
                    : item["type"] === 3
                      ? item["name"]
<<<<<<< HEAD
                      : item["type"] === 4
                        ? item["name"]
                        : "",
=======
                      : "",
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
              avatar:
                item["type"] === 1 ? this.lastName(item["realName"]) : "群聊",
              index: item["username"] && item["username"][0].toUpperCase(),
              unread: item["offlineMessageNumber"],
              login:
                item["erp9Login"] === 0 && item["xlLogin"] === 0 ? "离线" : "",
              lastContent:
                item["lastMessageType"] === 2
                  ? "[文件]"
                  : item["lastMessageType"] === 3
                    ? "[图片]"
                    : item["lastMessageType"] === 4
                      ? item["lastMessage"]
                      : item["lastMessageType"] === 5
                        ? item["lastMessage"]
                        : item["lastMessageType"] === 1
                          ? item["lastMessage"]
                          : " ",
              // toppingTime: new Date(item["toppingTime"]).getTime(),
              lastSendTime: new Date(item["lastMessageTime"]).getTime(),
              type: item["type"],
            });
            if (item.id == "Npc-Robot") {
              IMUI.updateContact({
                id: item["type"] == 1 ? item["username"] : item["groupId"],
                lastContent: item["lastMessageType"] == 6 ? item["lastMessage"] : item["lastMessageType"] == 7 ? item["lastMessage"] : item["lastMessage"],
                unread: item.offlineMessageNumber,
                login:
                  item["erp9Login"] === 0 && item["xlLogin"] === 0
                    ? ""
                    : "",
                lastSendTime: new Date(item["lastMessageTime"]).getTime(),
              });
            } else {
              IMUI.updateContact({
                id: item["type"] == 1 ? item["username"] : item["groupId"],
                displayName:
                  item["type"] === 1
                    ? item["realName"]
                    : item["type"] === 2
                      ? item["name"]
                      : item["type"] === 3
                        ? item["name"]
<<<<<<< HEAD
                        : item["type"] === 4
                          ? item["name"]
                          : "",
=======
                        : "",
>>>>>>> b81dd856e8286dc3c4469fe464d7cb70decd559d
                avatar:
                  item["type"] === 1 ? this.lastName(item["realName"]) : "群聊",
                index: item["username"] && item["username"][0].toUpperCase(),
                lastContent:
                  item["lastMessageType"] === 2
                    ? "[文件]"
                    : item["lastMessageType"] === 3
                      ? "[图片]"
                      : item["lastMessageType"] === 4
                        ? item["lastMessage"]
                        : item["lastMessageType"] === 5
                          ? item["lastMessage"]
                          : item["lastMessageType"] === 1
                            ? item["lastMessage"]
                            : " ",
                unread: item["offlineMessageNumber"],
                noReminder: !!item["noReminder"],
                login:
                  item["erp9Login"] === 0 && item["xlLogin"] === 0
                    ? "离线"
                    : "",
                toppingTime: new Date(item["toppingTime"]).getTime(),
                lastSendTime: new Date(item["lastMessageTime"]).getTime(),
                type: item["type"],
              });
            }
          });
          this.unreadMessage = 0;
          result.map((item) => {
            if (item.noReminder == 0) {
              this.unreadMessage =
                this.unreadMessage + item.offlineMessageNumber;
            }
          });
          if (this.unreadMessage > 0) {
            GetMessage(this.unreadMessage);
          }
          if (this.unreadMessage == 0) {
            if (IMUI.currentContactId !== null && result1.ifHaveNewMsg === 1) {
              GetMessage(-1);
            } else {
              GetMessage(0);
            }
          }
          this.$nextTick(() => {
            setTimeout(() => {
              IMUI.messageViewToBottom();
            }, 500);
          });
        }
      );
    },
    onFailed(error) {
      console.error("即时通信连接rabbitmq时报错监听最近联系人：" + error);
      window.setTimeout(() => {
        this.connect();
      }, 5000);
    },
    connect() {
      this.client = Stomp.client(urlConfig.rabbitmqUrl);
      this.client.heartbeat.outgoing = 5000;
      this.client.heartbeat.incoming = 5000;
      // this.client.debug = null;
      this.client.connect(
        "imend",
        urlConfig.rabbitmqPassword,
        this.onConnected,
        this.onFailed,
        "/"
      );
    },
    //监听撤回消息
    onConnectedRetraction(frame) {
      this.client.subscribe(
        `/exchange/im-end.retraction/${this.name}`,
        (data) => {
          let msg = data.body;
          console.log("收到的数据撤回消息", JSON.parse(msg));
          const result = JSON.parse(msg);
          if (result.type == 1) {
            const data = {
              id: result.message.id,
              type: "event",
              content: (
                <div>
                  <span>{result.message.fromUserRealName}撤回了一条消息</span>
                </div>
              ),
              toContactId: result.message.toUserAccount,
              sendTime: result.message.retractionTime,
            };
            this.$refs.IMUI.updateMessage(data);
          } else if (result.type == 2) {
            const data = {
              id: result.groupMessage.id,
              type: "event",
              content: (
                <div>
                  <span>
                    {result.groupMessage.fromUserRealName}撤回了一条消息
                  </span>
                </div>
              ),
              toContactId: result.groupMessage.toUserAccount,
              sendTime: result.groupMessage.retractionTime,
            };
            this.$refs.IMUI.updateMessage(data);
          } else if (result.type == 3) {
            const data = {
              id: result.userGroupMessage.id,
              type: "event",
              content: (
                <div>
                  <span>
                    {result.userGroupMessage.fromUserRealName}撤回了一条消息
                  </span>
                </div>
              ),
              toContactId: result.userGroupMessage.toUserAccount,
              sendTime: result.userGroupMessage.retractionTime,
            };
            this.$refs.IMUI.updateMessage(data);
          }
        }
      );
    },
    onFailedRetraction(error) {
      console.error("即时通信连接rabbitmq时报错监听撤回：" + error);
      window.setTimeout(() => {
        this.connectRetraction();
      }, 5000);
    },
    connectRetraction() {
      this.clientRetraction = Stomp.client(urlConfig.rabbitmqUrl);
      this.clientRetraction.heartbeat.outgoing = 5000;
      this.clientRetraction.heartbeat.incoming = 5000;
      // this.client.debug = null;
      this.clientRetraction.connect(
        "imend",
        urlConfig.rabbitmqPassword,
        this.onConnectedRetraction,
        this.onFailedRetraction,
        "/"
      );
    },
    //监听已读消息
    onConnectedRead(frame) {
      this.client.subscribe(`/exchange/im-end.read/${this.name}`, (data) => {
        let msg = data.body;
        console.log("收到的数据撤回消息1", JSON.parse(msg));
        const result = JSON.parse(msg);
        const { IMUI } = this.$refs;
        const message = IMUI.updateMessage({
          id: result,
          read: 2,
        });
        if (message === false) {
          setTimeout(() => {
            const message = IMUI.updateMessage({
              id: result,
              read: 2,
            });
          }, 3000);
        }
      });
    },
    onFailedRead(error) {
      console.error("即时通信连接rabbitmq时报错监听已读：" + error);
      window.setTimeout(() => {
        this.connectRead();
      }, 5000);
    },
    connectRead() {
      this.clientRead = Stomp.client(urlConfig.rabbitmqUrl);
      this.clientRead.heartbeat.outgoing = 5000;
      this.clientRead.heartbeat.incoming = 5000;
      // this.client.debug = null;
      this.clientRead.connect(
        "imend",
        urlConfig.rabbitmqPassword,
        this.onConnectedRead,
        this.onFailedRead,
        "/"
      );
    },
    //监听机构树队列
    onConnectedTreenode() {
      this.client.subscribe(
        `/exchange/im-end.treenode/${this.name}`,
        async (data) => {
          let msg = data.body;
          console.log("收到的数据", JSON.parse(msg));
          const msgResult = JSON.parse(msg);
          this.$refs.treeRef.refreshTreeNode(msgResult);
        }
      );
    },
    onFailedTreenode(error) {
      console.error("即时通信连接rabbitmq时报错监听机构树：" + error);
      window.setTimeout(() => {
        this.connectTreenode();
      }, 5000);
    },
    connectTreenode() {
      this.clientTreenode = Stomp.client(urlConfig.rabbitmqUrl);
      this.clientTreenode.heartbeat.outgoing = 5000;
      this.clientTreenode.heartbeat.incoming = 5000;
      // this.client.debug = null;
      this.clientTreenode.connect(
        "imend",
        urlConfig.rabbitmqPassword,
        this.onConnectedTreenode,
        this.onFailedTreenode,
        "/"
      );
    },
    //监听人员信息的变更
    onConnectedUser() {
      this.client.subscribe(`/exchange/im-end.account/${this.name}`, (data) => {
        let msg = data.body;
        console.log("收到的数据", JSON.parse(msg));
        const result = JSON.parse(msg);
        this.currentUserInfo = result;
        this.UserData.avatar = result.realName.substr(-2);
      });
    },
    onFailedUser(error) {
      console.error("即时通信连接rabbitmq时报错监听人员信息：" + error);
      window.setTimeout(() => {
        this.connectUser();
      }, 5000);
    },
    connectUser() {
      this.clientUser = Stomp.client(urlConfig.rabbitmqUrl);
      this.clientUser.heartbeat.outgoing = 5000;
      this.clientUser.heartbeat.incoming = 5000;
      // this.client.debug = null;
      this.clientUser.connect(
        "imend",
        urlConfig.rabbitmqPassword,
        this.onConnectedUser,
        this.onFailedUser,
        "/"
      );
    },
    //初始化左侧列表
    initMenus() {
      this.$refs.IMUI.initMenus([
        {
          name: "messages",
          renderContainer: () => {
            return;
          },
        },
        {
          name: "custom2",
          render: (menu) => {
            return (
              <div>
                <i class="lemon-icon-people" />
              </div>
            );
          },
          renderContainer: () => {
            return (
              <Contacts
                on-private={this.private}
                on-group={this.group}
                userId={this.id}
                name={this.name}
                type={this.type}
                ref="treeRef"
              />
            );
          },
        },
      ]);
    },
    //模糊查询用户和用户所在群
    handleSelect({ item, type }) {
      if (type == 1) {
        this.private(item);
      } else if (type == 2) {
        item.label = item.name;
        this.group(item);
      } else if (type == 3) {
        item.label = item.name;
        this.group(item);
      }
    },
    //退出群聊
    quitUserGroup(obj) {
      this.clearMessages();
      const IMUI = this.$refs.IMUI;
      this.getAccount(IMUI);
      this.$refs.IMUI.drawerVisible = false;
      this.drawerVisible = false;
    },
    // closeSearch() {
    //   this.searchResult = false;
    // },
    //关闭页面
    async handleClose() {
      let data = {
        type: 1,
        code: 200,
        data: "false",
      };
      window.parent.postMessage(data, "*");
    },
    // 切换左侧近期联系人聊天窗口时触发
    async changeNearContact(contact) {
      console.log("contact111111", contact);
      GetMessage(0);
      cachePageInfo.set(contact.id, 1);
      this.websocket1 && this.websocket1.close();
      // this.websocket1 = null;
      // this.currentWsGroupId = null;
      const pageNo = cachePageInfo.get(contact.id);
      if (contact.type == 2 || contact.type == 4) {
        this.initWebsocket1(`group/${contact.id}/${this.name}`, contact.id);
        const result = await this.$API.admins.groupNumber(contact.id);
        if (result.code === 200) {
          this.numberOnline = result.result;
        }
        const resultLastContactTime =
          await this.$API.admins.groupLastContactTime(
            contact.id,
            this.id,
            this.name
          );
        //默认群离线消息
        const groupOfflineResult = await this.$API.admins.groupOfflineMessage(
          contact.id,
          this.name
        );
        contact.unread = 0;
        if (this.toUser) {
          const updateResult = await this.$API.admins.updatechatPair(
            this.name,
            this.toUser,
            0
          );
        }
      } else if (contact.type == 3) {
        this.initWebsocket1(`userGroup/${contact.id}/${this.name}`, contact.id);
        
        const result = await this.$API.admins.userGroupNumber(contact.id);
        if (result.code === 200) {
          this.numberOnline = result.result;
        }
        //自定义群离线消息
        const userGroupOfflineResult = this.$API.admins.userGroupOfflineMessage(
          contact.id,
          this.name
        );
        contact.unread = 0;
        const resultLastContactTime =
          await this.$API.admins.userGroupLastContactTime(
            contact.id,
            this.id,
            this.name
          );
        if (this.toUser) {
          const updateResult = await this.$API.admins.updatechatPair(
            this.name,
            this.toUser,
            0
          );
        }
      } else if (contact.type == 1) {
        const result = await this.$API.admins.prosonalOffline(
          this.name,
          contact.id
        );
        this.numberOnline = "";
        //一对一离线消息
        const offlineResult = await this.$API.admins.offlineMessage(
          contact.id,
          this.name
        );
        if (offlineResult.code == 200) {
          contact.unread = 0;
        }
        const updateResult = await this.$API.admins.updatechatPair(
          this.name,
          contact.id,
          1
        );
        this.toUser = contact.id;
      }
      this.$store.commit("setCurrentContact", contact);
      this.initMenus();
      // const IMUI = this.$refs.IMUI;
      // this.getAccount(IMUI);
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.IMUI.messageViewToBottom();
        }, 500);
      });
    },
    //下载文件
    async handleMessageClick(event, key, message) {
      const type =
        message.type === "file" ? 2 : message.type === "image" ? 3 : 1;
      if (type === 3) {
        this.url = message.content;
      } else if (type === 2) {
        if (message.fileName) {
          // 删除文件名前边的路径，如im-end-dev/远大支持论坛_1654762887980.png，
          // 则转换为：远大支持论坛_1654762887980.png
          let fileNameArray = message.fileName && message.fileName.split("/");
          //开启遮罩层
          let loadingInstance = Loading.service({
            lock: true, //lock的修改符--默认是false
            text: "正在下载文件，请耐心等待", //显示在加载图标下方的加载文案
            spinner: "el-icon-loading", //自定义加载图标类名
            background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
            target: document.querySelector("#futureTransferDialog"), //loadin覆盖的dom元素节点
          });

          let downloadFileName = undefined;
          if (fileNameArray.length == 1) {
            downloadFileName = fileNameArray[0];
          } else {
            downloadFileName = fileNameArray[fileNameArray.length - 1];
          }
          // 下载文件
          await this.$API.admins
            .fileDownload({ filename: downloadFileName, type })
            .then((response) => {
              //关闭遮罩层
              loadingInstance.close();
              const blob = new Blob([response], { type: "" });
              saveAs(blob, message.fileName);
            })
            .catch((error) => {
              //关闭遮罩层
              loadingInstance.close();
              this.$message.error(error);
            });
        }
      }
    },
    //群
    group(obj) {
      this.$refs.IMUI.appendContact({
        id: obj["id"],
        displayName: obj["label"],
        pinYin: obj["id"],
        avatar: "群聊",
        index: "",
        unread: 0,
        lastContent: "",
        type: obj["type"],
      });

      this.$refs.IMUI.updateContact({ id: obj.id, lastContent: " " });
      this.$refs.IMUI.changeContact(obj.id, "messages");
      this.changeNearContact(this.$refs.IMUI.getCurrentContact());
    },
    //个人
    private(obj) {
      this.$refs.IMUI.appendContact({
        id: obj["username"],
        displayName: obj["realName"],
        pinYin: obj["username"],
        avatar: this.lastName(obj["realName"]),
        index: obj["username"] && obj["username"][0].toUpperCase(),
        lastSendTime: new Date(),
        unread: 0,
        login: obj["login"],
        lastContent: " ",
        type: obj["type"],
      });
      this.$refs.IMUI.updateContact({ id: obj.username, lastContent: " " });
      this.$refs.IMUI.changeContact(obj.username, "messages");
      this.changeNearContact(this.$refs.IMUI.getCurrentContact());
    },
    //创建群聊
    createGroup(groupName, id) {
      this.$refs.IMUI.appendContact({
        id: id,
        displayName: groupName,
        pinYin: id,
        avatar: "群聊",
        index: "",
        unread: 0,
        lastContent: "",
        type: 3,
      });
      console.log("tag", id, this.name);
      this.websocketParams = `userGroup/${id}/${this.name}`;
      this.initWebsocket1(`userGroup/${id}/${this.name}`, id);
      this.$refs.IMUI.updateContact({ id, lastContent: " " });
      this.$refs.IMUI.changeContact(id, "messages");
      this.changeNearContact(this.$refs.IMUI.getCurrentContact());
    },
    //自定义群添加新成员后的在线人数
    async addUserGroupAccount(obj) {
      const result = await this.$API.admins.userGroupNumber(obj.userGroup.id);
      if (result.code === 200) {
        this.numberOnline = result.result;
      }
      const IMUI = this.$refs;
      this.getAccount(IMUI);
    },
    //置顶聊天
    async top(status1) {
      const { id: toUserAccount } = this.$refs.IMUI.getCurrentContact();
      const type = this.$refs.IMUI.getCurrentContact().type;
      if (type === 1) {
        const fromUserAccount = this.name;
        const status = status1;
        const params = `${fromUserAccount}/${toUserAccount}/${status}`;
        const result = await this.$API.admins.topping(params);
      } else if (type === 2) {
        const groupId = this.$refs.IMUI.getCurrentContact().id;
        const accountId = this.id;
        const username = this.name;
        const status = status1;
        const params = `${groupId}/${accountId}/${username}/${status}`;
        const result = await this.$API.admins.groupToppingAccount(params);
      } else if (type === 3) {
        const userGroupId = this.$refs.IMUI.getCurrentContact().id;
        const accountId = this.id;
        const username = this.name;
        const status = status1;
        const params = `${userGroupId}/${accountId}/${username}/${status}`;
        const result = await this.$API.admins.userGroupToppingAccount(params);
      }
    },
    //消息免打扰
    async noReminder(noReminderStatus) {
      const type = this.$refs.IMUI.getCurrentContact().type;
      if (type === 1) {
        const fromUserAccount = this.name;
        const toUserAccount = this.$refs.IMUI.getCurrentContact().id;
        const status = noReminderStatus;
        const params = `${toUserAccount}/${fromUserAccount}/${status}`;
        const result = await this.$API.admins.personNoReminder(params);
      } else if (type === 2) {
        const groupId = this.$refs.IMUI.getCurrentContact().id;
        const accountId = this.id;
        const username = this.name;
        const status = noReminderStatus;
        const params = `${groupId}/${accountId}/${username}/${status}`;
        const result = await this.$API.admins.groupNoReminder(params);
      } else if (type === 3) {
        const userGroupId = this.$refs.IMUI.getCurrentContact().id;
        const accountId = this.id;
        const username = this.name;
        const status = noReminderStatus;
        const params = `${userGroupId}/${accountId}/${username}/${status}`;
        const result = await this.$API.admins.userGroupNoReminder(params);
      }
    },
    onopen(e) {
      console.log("已连接服务端");
    },
    onopen1(e) {
      console.log("群聊 ws 打开");
    },
    //获取后端消息一对一
    async onmessage(evt) {
      let {
        content,
        fromUserAccount,
        toUserAccount,
        fromUserRealName,
        type,
        filePath,
        id,
        vueId,
      } = JSON.parse(evt.data);
      const { IMUI } = this.$refs;
      const index = IMUI.lastMessages.findIndex(
        (item) => item.id === fromUserAccount
      );
      if (index > -1) {
      } else {
        IMUI.appendContact({
          id: fromUserAccount,
          displayName: fromUserRealName,
          avatar: fromUserRealName.substr(-2),
          type: 1,
        });
      }
      const data = {
        id: id,
        status: "succeed",
        type: type === 2 ? "file" : type === 3 ? "image" : "text",
        sendTime: new Date().getTime(),
        content: type === 1 ? content : type === 3 ? filePath : "",
        fileName: type !== 1 ? filePath && filePath.split("/")[1] : null,
        toContactId:
          toUserAccount === this.name ? fromUserAccount : toUserAccount,
        fromUser: {
          id: fromUserAccount,
          displayName: "",
          avatar: fromUserRealName && this.lastName(fromUserRealName),
        },
      };
      if (this.name === fromUserAccount) {
        const newId = this.mids.shift();
        const flag = this.$refs.IMUI.updateMessageById(newId, { id: id });
        if (!flag) {
          IMUI.appendMessage(data, true);
        }
      } else {
        IMUI.appendMessage(data, true);
      }
      // if (fromUserAccount == IMUI.currentContactId && this.unreadMessage == 0) {
      //   console.log("88888888");
      //   setTimeout(() => {
      //     GetMessage(-1);
      //   },500)

      // }
      //收到服务器信息
      console.log(`数据已接收`, JSON.parse(evt.data));
      this.$nextTick(() => {
        setTimeout(() => {
          IMUI.messageViewToBottom();
        }, 500);
      });
    },
    //获取接受后端消息群聊
    onmessage1(evt) {
      let { fromUserAccount, content, fromUserRealName, type, filePath } =
        JSON.parse(evt.data);
      const { IMUI } = this.$refs;
      const groupData = JSON.parse(evt.data);
      const groupId = groupData.groupId
        ? groupData.groupId
        : groupData.userGroupId;
      const id = groupData.groupMessageId
        ? groupData.groupMessageId
        : groupData.userGroupMessageId;
      const index = IMUI.lastMessages.findIndex(
        (item) => item.id === IMUI.getCurrentContact().id
      );
      if (index > -1) {
      } else {
        IMUI.appendContact({
          id: groupId,
          displayName: fromUserRealName,
          avatar: "群聊",
          type: type,
        });
      }
      const data = {
        id: id,
        status: "succeed",
        // type: type === 1 ? "text" : 'file',
        type: type === 2 ? "file" : type === 3 ? "image" : "text",
        sendTime: new Date().getTime(),
        content: type === 1 ? content : type === 3 ? filePath : "",
        fileName: type !== 1 ? filePath && filePath.split("/")[1] : null,
        toContactId: groupId,
        fromUser: {
          //如果 id == this.user.id消息会显示在右侧，否则在左侧
          id: fromUserAccount,
          displayName: "",
          avatar: fromUserRealName && this.lastName(fromUserRealName),
        },
      };
      if (this.name === fromUserAccount) {
        // GetMessage(0);
        const newId = this.mids.shift();
        const flag = this.$refs.IMUI.updateMessageById(newId, { id: id });
        if (!flag && type !== 4 && type !== 5) {
          IMUI.appendMessage(data, true);
        }
      } else {
        if (type !== 4 && type !== 5) {
          IMUI.appendMessage(data, true);
        }
        // if (groupId == IMUI.currentContactId && this.unreadMessage == 0) {
        //   GetMessage(-1);
        // }
      }

      //收到服务器信息
      console.log(`数据已接收`, JSON.parse(evt.data));
      this.$nextTick(() => {
        setTimeout(() => {
          IMUI.messageViewToBottom();
        }, 500);
      });
      // this.getAccount(IMUI);
    },
    onclose(e) {
      console.log("单聊连接已关闭...");
    },
    onclose1() {
      console.log("群聊连接已关闭...");
    },
    onerror() {
      console.log("连接失败...");
      this.websocket = new WebSocket(
        `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${this.name}/`,
        "Authorization'4f52f26643d647b9b6a4e94c1147f9c2"
      );
      this.websocket.onopen = this.onopen;

      this.websocket.onmessage = this.onmessage;

      this.websocket.onclose = this.onclose;

      this.websocket.onerror = this.onerror;
    },
    onerror1() {
      console.log("连接失败...");
      this.websocket1 = new WebSocket(
        `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${this.websocketParams}/`,
        "Authorization'4f52f26643d647b9b6a4e94c1147f9c2"
      );
      this.websocket1.onopen = this.onopen1;

      this.websocket1.onmessage = this.onmessage1;

      this.websocket1.onclose = this.onclose1;

      this.websocket1.onerror = this.onerror1;
    },
    //清空聊天记录
    clearMessages(contact_id) {
      this.$refs.IMUI.clearMessages(contact_id);
    },
    //抽屉
    changeDrawer(contact) {
      this.$store.commit("setCurrentContact", contact);
      this.$refs.IMUI.changeDrawer({
        width: 240,
        position: "rightInside",
        marginTop: 41,
        render: () => {
          return (
            <div class="drawer-content" ref="drawer">
              <Sidebar
                on-top={this.top}
                on-noReminder={this.noReminder}
                on-createGroup={this.createGroup}
                on-quitUserGroup={this.quitUserGroup}
                on-clearMessages={this.clearMessages}
                on-addUserGroupAccount={this.addUserGroupAccount}
                userId={this.id}
                name={this.name}
              />
            </div>
          );
        },
      });
      this.drawerVisible = this.$refs.IMUI.drawerVisible;
    },
    //获取账号信息
    async getLogin() {
      this.initWebsocket();
      const result = await this.$API.admins.login(this.id);
      if (result.code === 200) {
        this.UserData = {
          id: result.result.username,
          displayName: result.result.realName,
          avatar: this.lastName(result.result.realName),
        };
        //将当前用户得信息存入vuex中
        this.$store.commit("setUser", result.result);
      }
    },

    async getUser() {
      const result = await this.$API.admins.login(this.id);
      if (result.code === 200) {
        this.currentUserInfo = result.result;
      }
    },

    //获取近期联系人
    async getAccount(IMUI) {
      const result = await this.$API.admins.allPerson(this.name);
      const arr = [];
      result.result.forEach((item, index) => {
        if (item.username == "Npc-Robot") {
          arr.push({
            id: item["type"] === 1 ? item["username"] : item["id"],
            privateId: item["id"],
            displayName:
              item["type"] === 1
                ? item["realName"]
                : item["type"] === 2
                  ? item["name"]
                  : item["name"],
            avatar:
              item["type"] === 1 ? this.lastName(item["realName"]) : "群聊",
            index: item["id"] && item["id"][0].toUpperCase(),
            unread: item["offlineMessageNumber"],
            noReminder: !!item["noReminder"],
            login:
              item["erp9Login"] === 0 && item["xlLogin"] === 0 ? "" : "",
            lastContent: item["lastMessageType"] == 6 ? item["lastMessage"] : item["lastMessageType"] == 7 ? item["lastMessage"] : item["lastMessage"],
            toppingTime: new Date(item["toppingTime"]).getTime(),
            lastSendTime: new Date(item["lastMessageTime"]).getTime(),
            type: item["type"],
          });
        } else {
          arr.push({
            id: item["type"] === 1 ? item["username"] : item["id"],
            privateId: item["id"],
            displayName:
              item["type"] === 1
                ? item["realName"]
                : item["type"] === 2
                  ? item["name"]
                  : item["name"],
            avatar:
              item["type"] === 1 ? this.lastName(item["realName"]) : "群聊",
            index: item["id"] && item["id"][0].toUpperCase(),
            unread: item["offlineMessageNumber"],
            noReminder: !!item["noReminder"],
            login:
              item["erp9Login"] === 0 && item["xlLogin"] === 0 ? "离线" : "",
            lastContent:
              item["lastMessageType"] === 2
                ? "[文件]"
                : item["lastMessageType"] === 3
                  ? "[图片]"
                  : item["lastMessageType"] === 4
                    ? item["lastMessage"]
                    : item["lastMessageType"] === 5
                      ? item["lastMessage"]
                      : item["lastMessageType"] === 1
                        ? item["lastMessage"]
                        : " ",
            toppingTime: new Date(item["toppingTime"]).getTime(),
            lastSendTime: new Date(item["lastMessageTime"]).getTime(),
            type: item["type"],
          });
        }
      });
      this.unreadMessage = 0;
      result.result.map((item) => {
        this.unreadMessage = this.unreadMessage + item.offlineMessageNumber;
      });
      if (this.unreadMessage > 0) {
        GetMessage(this.unreadMessage);
      }
      console.log('tag', IMUI)
      // const sortResult = await this.$API.admins.sort(this.name)
      IMUI.initContacts(arr);
      this.initMenus();
    },
    lastName(name) {
      return name.substr(-2);
    },
    //拉取消息
    async handlePullMessages(contact, next) {
      const contactId = contact.id;
      console.log(contact, "66666666666666666666666");
      if (!contactId) {
        return next();
      }
      this.$refs.IMUI.updateContact({ id: contactId, unread: 0 });
      const pageSize = 20;
      if (!cachePageInfo.has(contactId)) {
        cachePageInfo.set(contactId, 1);
      }
      const pageNo = cachePageInfo.get(contactId);

      if (contact.type === 2 || (contact.type === 4 && contactId)) {
        //获取默认群聊天记录
        const fromUserAccount = this.name;
        const type = 0;
        const params = `${contactId}/${fromUserAccount}/${pageSize}/${pageNo}/${type}`;
        const result = await this.$API.admins.GroupMessage(params);
        cachePageInfo.set(contactId, cachePageInfo.get(contactId) + 1);
        if (result.result.length === 0) {
          next([], true);
        }
        const result_msgGroup = [];
        // for (let i = result.result.length - 1; i >= 0; i--) {
        for (let i = 0; i < result.result.length; i++) {
          let item = result.result[i];
          if (item.type === 4) {
            result_msgGroup.push({
              id: item.id,
              type: "event",
              content: (
                <span>
                  {this.name == item.fromUserAccount
                    ? "你撤回了一条消息"
                    : item.content}
                </span>
              ),
              edit: (
                <span
                  v-show={this.name == item.fromUserAccount}
                  style="color:#333;cursor:pointer"
                  content={item.retractionContent}
                  on-click={(e) => {
                    this.$refs.IMUI.setEditorValue(
                      e.target.getAttribute("content")
                    );
                  }}
                >
                  重新编辑
                </span>
              ),
              toContactId: item.groupId,
              sendTime: new Date(item.createTime).getTime(),
            });
          } else {
            if (item.retractionTime == null) {
              result_msgGroup.push({
                id: item["id"],
                status: "succeed",
                type:
                  item["type"] === 2
                    ? "file"
                    : item["type"] === 3
                      ? "image"
                      : "text",
                content:
                  item["type"] === 1
                    ? item["content"]
                    : item["type"] == 4
                      ? item["content"]
                      : item["type"] === 3
                        ? item["filePath"]
                        : "",
                fileName: item["type"] !== 1 ? item["filePath"] : "",
                sendTime: new Date(item["createTime"]).getTime(),
                toContactId: item["toUserAccount"],
                fromUser: {
                  id: item["fromUserAccount"],
                  displayName: "",
                  avatar:
                    item["fromUserRealName"] &&
                    this.lastName(item["fromUserRealName"]),
                },
              });
            }
          }
        }
        //获取默认群在线人数
        // const groupResult = await this.$API.admins.groupNumber(contactId);
        if (result.result.length < pageSize) {
          next(result_msgGroup, true);
        } else {
          next(result_msgGroup);
        }
        // this.$nextTick(() => {
        //   setTimeout(() => {
        //     this.$refs.IMUI.messageViewToBottom();
        //   }, 500);
        // });
      } else if (contact.type === 3 && contactId) {
        //获取自定义群聊天记录
        const fromUserAccount = this.name;
        const type = 0;
        const params = `${contactId}/${fromUserAccount}/${pageSize}/${pageNo}/${type}`;
        const result = await this.$API.admins.userGroupMessage(params);
        console.log("tag", result.result);
        cachePageInfo.set(contactId, cachePageInfo.get(contactId) + 1);
        if (result.result.length === 0) {
          next([], true);
        }
        const result_userGroup = [];
        for (let i = 0; i < result.result.length; i++) {
          let item = result.result[i];
          if (item.type == 4) {
            result_userGroup.push({
              id: item.id,
              type: "event",
              content: (
                <span>
                  {this.name == item.fromUserAccount
                    ? "你撤回了一条消息"
                    : item.content}
                </span>
              ),
              edit: (
                <span
                  v-show={this.name == item.fromUserAccount}
                  style="color:#333;cursor:pointer"
                  content={item.retractionContent}
                  on-click={(e) => {
                    this.$refs.IMUI.setEditorValue(
                      e.target.getAttribute("content")
                    );
                  }}
                >
                  重新编辑
                </span>
              ),
              toContactId: item.userGroupId,
              sendTime: new Date(item.createTime).getTime(),
            });
          } else if (item.type == 5) {
            result_userGroup.push({
              id: item.id,
              type: "event",
              content: item.content,
              toContactId: item.userGroupId,
              sendTime: new Date(item.createTime).getTime(),
            });
          } else {
            // console.log(item.retractionTime)
            if (item.retractionTime == null) {
              result_userGroup.push({
                id: item["id"],
                status: "succeed",
                type:
                  item["type"] === 2
                    ? "file"
                    : item["type"] === 3
                      ? "image"
                      : "text",
                content:
                  item["type"] === 1
                    ? item["content"]
                    : item["type"] == 4
                      ? item["content"]
                      : item["type"] === 3
                        ? item["filePath"]
                        : "",
                fileName: item["type"] !== 1 ? item["filePath"] : "",
                sendTime: new Date(item["createTime"]).getTime(),
                toContactId: item["toUserAccount"],
                fromUser: {
                  id: item["fromUserAccount"],
                  displayName: "",
                  avatar:
                    item["fromUserRealName"] &&
                    this.lastName(item["fromUserRealName"]),
                },
              });
            }
          }
        }
        if (result.result.length < pageSize) {
          next(result_userGroup, true);
        } else {
          next(result_userGroup);
        }
        // this.$nextTick(() => {
        //   setTimeout(() => {
        //     this.$refs.IMUI.messageViewToBottom();
        //   }, 500);
        // });
      } else {
        const fromUserAccount = this.name;
        const type = 0;
        const params = `${fromUserAccount}/${contactId}/${pageSize}/${pageNo}/${type}`;
        //获取聊天记录
        const result = await this.$API.admins.getMessage(params);
        cachePageInfo.set(contactId, cachePageInfo.get(contactId) + 1);
        if (result.result.length === 0) {
          next([], true);
        }
        const { avatar } = this.$refs.IMUI.getCurrentContact();
        const result_msg = [];
        for (let i = 0; i < result.result.length; i++) {
          let item = result.result[i];
          if (item.type == 4 && contactId !== "Npc-Robot") {
            result_msg.push({
              id: item.id,
              type: "event",
              content: item.content,
              edit: (
                <span
                  v-show={this.name == item.fromUserAccount}
                  style="color:#333;cursor:pointer"
                  content={item.retractionContent}
                  on-click={(e) => {
                    this.$refs.IMUI.setEditorValue(
                      e.target.getAttribute("content")
                    );
                  }}
                >
                  重新编辑
                </span>
              ),
              toContactId: item.fromUserAccount,
              sendTime: new Date(item.createTime).getTime(),
            });
          } else if (contactId == "Npc-Robot") {
            let newContent = JSON.parse(item.content);
            let url = newContent.Url;
            if (item.type == 6) {
              result_msg.push({
                id: item.id,
                type: "event",
                class: "npc",
                content: (
                  <div style="width:500px;background:#fff;">
                    <span style="display:block;padding:10px 20px;background:linear-gradient(to right,#FFF5EE,#FFFFFF);color:#333;font-size:15px;">
                      <i
                        class="el-icon-shopping-bag-2"
                        style="color:#e9ab7f;font-size:20px;margin-right:5px;"
                      ></i>
                      公告栏提醒
                    </span>
                    <el-divider style="border: 1px dashed #cf9118a3;"></el-divider>
                    <span style="display:block;padding:10px 20px;color:#666;font-size:12px;">
                      您有一封邮件待查收：
                    </span>
                    <div style="padding:0 20px 0;">
                      <p style="display:flex">
                        <span style="color:#c0c4cc;margin-right:30px;font-size:12px;">
                          邮件标题
                        </span>
                        <span
                          style="color:#333;font-size:12px;width:83%"
                          domPropsInnerHTML={newContent.Title}
                        ></span>
                      </p>
                      <p style="display:flex">
                        <span style="color:#c0c4cc;margin-right:30px;font-size:12px;">
                          邮件类别
                        </span>
                        <span style="color:#333;font-size:12px;width:83%">
                          {newContent.Type}
                        </span>
                      </p>
                      <p>
                        <span style="color:#c0c4cc;margin-right:43px;font-size:12px;">
                          发件人
                        </span>
                        <span style="color:#333;font-size:12px;">
                          {newContent.Authors}
                        </span>
                      </p>
                    </div>
                    <div style="margin:20px 0 10px 20px;color:#333;font-size:12px;">
                      <span>请到</span>
                      <a
                        style="color:rgb(211 108 19 / 97%);text-decoration:none;"
                        href={url}
                        target="_blank"
                      >
                        {" "}
                        &lt;公告栏 &gt;
                      </a>
                      <span>查看</span>
                    </div>
                  </div>
                ),
                toContactId: item.fromUserAccount,
                sendTime: new Date(item.createTime).getTime(),
              });
            } else if (item.type == 7) {
              result_msg.push({
                id: item.id,
                type: "event",
                class: "npc",
                content: (
                  <div style="width:500px;background:#fff;">
                    <span style="display:block;padding:10px 20px;background:linear-gradient(to right,#EEF9FF,#FFFFFF);color:#333;font-size:15px;">
                      <i
                        class="el-icon-tickets"
                        style="color:#3a8ee6;font-size:20px;margin-right:5px;"
                      ></i>
                      二次比价任务提醒
                    </span>
                    <el-divider style="border: 1px dashed #cf9118a3;"></el-divider>
                    <span style="display:block;padding:10px 20px;color:#666;font-size:12px;">
                      您有一封邮件待查收：
                    </span>
                    <div style="padding:0 20px 0;">
                      <p style="display:flex">
                        <span style="color:#c0c4cc;margin-right:30px;font-size:12px;">
                          邮件标题
                        </span>
                        <span style="color:#333;font-size:12px;width:83%;">
                          {newContent.Message}
                          {newContent.NoCode}
                        </span>
                      </p>
                      <p>
                        <span style="color:#c0c4cc;margin-right:30px;font-size:12px;">
                          邮件类型
                        </span>
                        <span style="color:#333;font-size:12px;">二次比价</span>
                      </p>
                    </div>
                    <div style="margin:20px 0 10px 20px;color:#333;font-size:12px;">
                      <span>请到</span>
                      <a
                        style="color:#3a8ee6;text-decoration:none;"
                        href={url}
                        target="_blank"
                      >
                        {" "}
                        &lt;我的比价任务 &gt;
                      </a>
                      <span>查看</span>
                    </div>
                  </div>
                ),
                toContactId: item.fromUserAccount,
                sendTime: new Date(item.createTime).getTime(),
              });
            } else if (item.type == 8) {
              result_msg.push({
                id: item.id,
                type: "event",
                class: "npc",
                content: (
                  <div style="width:500px;background:#fff;">
                    <span style="display:block;padding:10px 20px;background:linear-gradient(to right,#FFF2F2,#FFFFFF);color:#333;font-size:15px;">
                      <i
                        class="el-icon-bell"
                        style="color:#d5273f;font-size:20px;margin-right:5px;"
                      ></i>
                      销售订单推送失败
                    </span>
                    <el-divider style="border: 1px dashed #cf9118a3;"></el-divider>
                    <span style="display:block;padding:10px 20px;color:#666;font-size:12px;">
                      您有一封邮件待查收：
                    </span>
                    <div style="padding:0 20px 0;">
                      <p style="display:flex">
                        <span style="color:#c0c4cc;margin-right:30px;font-size:12px;
                        ">
                          邮件标题
                        </span>
                        <span
                          style="color:#333;font-size:12px;width:83%;"
                          domPropsInnerHTML={newContent.Text}
                        >
                          <span style="color:#d5273f;margin-left:5px;">
                            推送失败
                          </span>
                        </span>
                      </p>
                      <p>
                        <span style="color:#c0c4cc;margin-right:30px;font-size:12px;">
                          邮件类型
                        </span>
                        <span style="color:#333;font-size:12px;">销售订单</span>
                      </p>
                      <p>
                        <span style="color:#c0c4cc;margin-right:27px;font-size:12px;">
                          备注
                        </span>
                        <span style="color:#333;font-size:12px;margin-left:27px;">
                          {newContent.Summary}
                        </span>
                      </p>
                    </div>
                    <div style="margin:20px 0 10px 20px;color:#333;font-size:12px;">
                      <span>请到</span>
                      <a
                        style="color:#d5273f;text-decoration:none;"
                        href={url}
                        target="_blank"
                      >
                        {" "}
                        &lt;我的订单 &gt;
                      </a>
                      <span>查看</span>
                    </div>
                  </div>
                ),
                toContactId: item.fromUserAccount,
                sendTime: new Date(item.createTime).getTime(),
              });
            }
            else {
              result_msg.push({
                id: item["id"],
                status: "succeed",
                type:
                  item["type"] === 2
                    ? "file"
                    : item["type"] === 3
                      ? "image"
                      : "text",
                content:
                  item["type"] === 1
                    ? item["content"]
                    : item["type"] == 4
                      ? item["content"]
                      : item["type"] === 3
                        ? item["filePath"]
                        : "",
                read: item["read"],
                readTime: item["readTime"],
                retractionTime: item["retractionTime"],
                fileName: item["type"] !== 1 ? item["filePath"] : "",
                sendTime: new Date(item["createTime"]).getTime(),
                toContactId: item["toUserAccount"],
                fromUser: {
                  id: item["fromUserAccount"],
                  displayName: "",
                  avatar:
                    item["fromUserRealName"] &&
                    this.lastName(item["fromUserRealName"]),
                },
                toContactId: item.fromUserAccount,
                sendTime: new Date(item.createTime).getTime(),
              });
            }

            // result_msg.push({
            //   id: item.id,
            //   type: "event",
            //   class: "npc",
            //   content: (
            //     <div style="width:500px;background:#fff;">
            //       <span style="display:block;padding:10px 20px;background:linear-gradient(to right,#FFF2F2,#FFFFFF);color:#333;font-size:15px;">
            //         <i
            //           class="el-icon-bell"
            //           style="color:#d5273f;font-size:20px;margin-right:5px;"
            //         ></i>
            //         销售订单推送失败
            //       </span>
            //       <el-divider style="border: 1px dashed #cf9118a3;"></el-divider>
            //       <span style="display:block;padding:10px 20px;color:#666;font-size:14px;">
            //         您有一封邮件待查收：
            //       </span>
            //       <div style="padding:0 20px 0;">
            //         <p>
            //           <span style="color:#c0c4cc;;margin-right:30px;font-size:14px;">邮件标题</span>
            //           <span style="color:#333;font-size:14px;display:inline-block" domPropsInnerHTML={newContent.Text}><span style="color:#d5273f;margin-left:5px;">推送失败</span></span>
            //         </p>
            //         <p>
            //           <span style="color:#c0c4cc;margin-right:30px;font-size:14px;">邮件类型</span>
            //           <span style="color:#333;font-size:14px;">销售订单</span>
            //         </p>
            //         <p>
            //           <span style="color:#c0c4cc;;margin-right:30px;font-size:14px;">备注</span>
            //           <span style="color:#333;font-size:14px;margin-left:27px;">{newContent.Summary}</span>
            //         </p>
            //       </div>
            //       <div style="margin:20px 0 10px 20px;color:#333;font-size:14px;">
            //         <span>请到</span>
            //         <a style="color:#d5273f;text-decoration:none;" href={url} target="_blank"> &lt;我的订单 &gt;</a>
            //         <span>查看</span>
            //       </div>
            //     </div>
            //   ),
            //   toContactId: item.fromUserAccount,
            //   sendTime: new Date(item.createTime).getTime(),
            // });
          } else {
            if (item.retractionTime == null) {
              result_msg.push({
                id: item["id"],
                status: "succeed",
                type:
                  item["type"] === 2
                    ? "file"
                    : item["type"] === 3
                      ? "image"
                      : "text",
                content:
                  item["type"] === 1
                    ? item["content"]
                    : item["type"] == 4
                      ? item["content"]
                      : item["type"] === 3
                        ? item["filePath"]
                        : "",
                read: item["read"],
                readTime: item["readTime"],
                retractionTime: item["retractionTime"],
                fileName: item["type"] !== 1 ? item["filePath"] : "",
                sendTime: new Date(item["createTime"]).getTime(),
                toContactId: item["toUserAccount"],
                fromUser: {
                  id: item["fromUserAccount"],
                  displayName: "",
                  avatar:
                    item["fromUserRealName"] &&
                    this.lastName(item["fromUserRealName"]),
                },
              });
            }
          }
        }
        if (result.result.length < pageSize) {
          next(result_msg, true);
        } else {
          next(result_msg);
        }
        // this.$nextTick(() => {
        //   setTimeout(() => {
        //     this.$refs.IMUI.messageViewToBottom();
        //   }, 500);
        // });
      }
    },
    async handleChangeContact(contact, instance) {
      this.oldName = contact.displayName;
      const { IMUI } = this.$refs;
      this.$nextTick(() => {
        setTimeout(() => {
          IMUI.messageViewToBottom();
        }, 500);
      });
    },
    handleChangeMenu(name) {
      console.log("Event:change-menu", name);
    },
    //点击头像展示详细信息
    handleMenuAvatarClick() {
      this.userInfo = true;
      this.getUser();
    },
    //点击隐藏详细信息
    model() {
      this.userInfo = false;
    },
    async uploadWebsocket(params, id) {
      return await new Promise((resolve, reject) => {
        if (this.type == 1) {
          uploadWs[id] = new WebSocket(
            `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${params}/`,
            "Authorization'4f52f26643d647b9b6a4e94c1147f9c2"
          );
        } else {
          uploadWs[id] = new WebSocket(
            `${urlConfig.webSocketUrl}im-end-web-cluster/ws/v1/${params}/`,
            "Authorization'907d64edbed348879e988334c6343deb"
          );
        }
        uploadWs[id].onopen = function () {
          resolve(uploadWs[id]);
        };

        uploadWs[id].onmessage = this.uploadOnMsg;

        uploadWs[id].onclose = this.uploadOnClose;

        uploadWs[id].onerror = this.uploadOnError;
        window.setInterval(() => {
          //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
          let ping = { type: -1 };
          uploadWs[id].send(JSON.stringify(ping));
        }, 5000);
      });
    },
    uploadOnMsg(e) {
      console.log("上传文件成功:", e.data);
    },
    uploadOnClose() {
      console.log("上传文件ws关闭..");
    },
    uploadOnError(error) {
      console.log("上传文件错误.." + error);
    },
    readAsArrayBuffer(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = function () {
          resolve(this.result);
        };
      });
    },
    getCurrentContact() {
      return this.$refs.IMUI.getCurrentContact();
    },

    //发送消息
    handleSend(message, next, file) {
      // 当前聊天窗口联系人信息
      const {
        id: toUserAccount,
        type: messageType,
        displayName,
      } = this.getCurrentContact();
      const {
        fromUser: { id: fromUserAccount, displayName: realName },
        content,
        toContactId,
      } = message;

      this.mids.push(message.id);

      const type =
        message.type === "file" ? 2 : message.type === "image" ? 3 : 1;
      if (type !== 1) {
        var pattern = new RegExp(
          "[`~!@#$^&*=|{}':;',\\[\\]<>《》/?~！@#￥……&*——|{}【】‘；：”“'。，、？%]"
        );
        if (pattern.test(file.name)) {
          next({ status: "failed" });
          this.$message.error("文件名不合法，请修改！");
          return;
        }
      }
      if (messageType === 1) {
        let msg = {
          content: type === 1 ? content : "",
          fromUserRealName: realName,
          toUserRealName: displayName,
          type,
          read: 1,
          vueId: message.id,
        };
        if (type !== 1) {
          let msg = {
            content: type === 1 ? content : "",
            fromUserRealName: realName,
            toUserRealName: displayName,
            type,
            vueId: message.id,
          };
          // 文件重命名，格式：文件名前缀_时间戳.文件扩展名
          let index = file.name.lastIndexOf(".");
          let prefixName = file.name.substring(0, index);
          let suffixName = file.name.substring(index + 1, file.name.length);
          let newFileName = prefixName + "." + suffixName;
          message.fileName = newFileName;
          if (msg.type === 3) {
            newFileName =
              prefixName + "." + new Date().getTime() + "." + suffixName;
          }
          this.uploadWebsocket(
            `upload/${fromUserAccount}/${toUserAccount}/${newFileName}/${type}`,
            message.id
          )
            .then((ws) => {
              this.readAsArrayBuffer(file).then((ret) => {
                ws.send(ret);
              });
            })
            .catch((err) => {
              this.$message.error("发送失败，稍后请重试");
            });
          msg = { ...msg, fromUserAccount, toUserAccount };
        } else {
          msg = { ...msg, fromUserAccount, toUserAccount };
          this.websocket.send(JSON.stringify(msg));
        }
      } else if (messageType === 2 || messageType === 4) {
        let msg = {
          fromUserAccount,
          content,
          type,
          fromUserRealName: realName,
          vueId: message.id,
        };
        if (type !== 1) {
          let index = file.name.lastIndexOf(".");
          let prefixName = file.name.substring(0, index);
          let suffixName = file.name.substring(index + 1, file.name.length);
          let newFileName = prefixName + "." + suffixName;
          message.fileName = newFileName;
          if (msg.type == 3) {
            newFileName =
              prefixName + "." + new Date().getTime() + "." + suffixName;
          }
          this.uploadWebsocket(
            `group/upload/${toUserAccount}/${fromUserAccount}/${newFileName}/${type}`,
            message.id
          )
            .then((ws) => {
              this.readAsArrayBuffer(file).then((ret) => {
                ws.send(ret);
                // this.uploadWs.close();
              });
            })
            .catch((err) => {
              this.$message.error("发送失败，稍后请重试");
            });
          msg = { ...msg, groupId: toContactId };
        } else {
          msg = { ...msg, groupId: toContactId };
          this.websocket1.send(JSON.stringify(msg));
        }
      } else if (messageType === 3) {
        let msg = {
          fromUserAccount,
          content,
          type,
          fromUserRealName: realName,
          vueId: message.id,
        };
        if (type !== 1) {
          let index = file.name.lastIndexOf(".");
          let prefixName = file.name.substring(0, index);
          let suffixName = file.name.substring(index + 1, file.name.length);
          let newFileName = prefixName + "." + suffixName;
          message.fileName = newFileName;
          if (msg.type == 3) {
            newFileName =
              prefixName + "." + new Date().getTime() + "." + suffixName;
          }
          this.uploadWebsocket(
            `userGroup/upload/${toUserAccount}/${fromUserAccount}/${newFileName}/${type}`,
            message.id
          )
            .then((ws) => {
              this.readAsArrayBuffer(file).then((ret) => {
                ws.send(ret);
                // this.uploadWs.close();
              });
            })
            .catch((err) => {
              this.$message.error("发送失败，稍后请重试");
            });
          msg = { ...msg, userGroupId: toContactId };
        } else {
          msg = { ...msg, userGroupId: toContactId };
          this.websocket1.send(JSON.stringify(msg));
        }
      }
      setTimeout(() => {
        next();
        this.$refs.IMUI.messageViewToBottom();
      }, 100);
    },
  },
};
</script>
<style>
.el-divider--horizontal {
  margin: 0 !important;
}
</style>
<style lang="less">
.lemon-avatar {
  font-size: 12px !important;
  background: url(../assets/head.png) !important;
  background-size: cover !important;

  &.lemon-menu__avatar {
    color: #fff;
  }
}

.lemon-menu__item--active {
  color: #fff !important;
}

.lemon-model {
  z-index: 0 !important;
}

.qq-lemon-imui {
  // width: 52.55%;
  // position: absolute;
  // left: 26%;
  // top: 50%;
  // transform: translate(-50%, -50%);
  height: 100%;
  overflow: hidden;

  @media screen and (min-width: 450px) and (min-width: 720px) {
    width: 100%;
  }

  @media screen and (min-width: 720px) and (min-width: 900px) {
    width: 100%;
  }

  @media screen and (min-width: 900px) and (max-width: 1280px) {
    width: 100%;
  }

  @media screen and (min-width: 1280px) and (max-width: 1920px) {
    width: 100%;
  }
}

// .lemon-wrapper lemon-wrapper--theme-default {
// }
.lemon-messages {
  border-bottom: 1px solid #bbbbbb6b;
}

.lemon-message__content {
  background-color: #f8f8f9;
}

.lemon-message-image {
  .lemon-message__inner {
    width: 200px;
  }
}

&.lemon-slot {
  background: #ffffff;
  width: 100% !important;
  height: 100% !important;
}

.lemon-menu {
  width: 70px !important;
  background: #448be2 !important;
  border: 1px solid #bbbbbb !important;
}

.main {
  width: 250px;
  height: 100%;
  border-right: 1px solid #eee;
}

.lemon-container {
  height: 100%;

  .container {
    height: 100%;
  }
}

.lemon-message-event__content {
  padding: 2px 2px !important;
}

.lemon-contextmenu__item:hover {
  background: #e2e1e1;
}

.previewImage {
  width: 100%;
  height: 100%;
}

.search {
  position: absolute;
  bottom: 184px;
  left: 55px;
}

.lemon-sidebar {
  // width: 266px;
  // height: 527px;
  background: #f8f8f9;
  // margin-top: 72px;
  z-index: 0 !important;
}

.lemon-container {
  background: #fff;
}

.lemon-vessel__left {
  transition: 0.3s;
}

.lemon-vessel__right {
  border-left: 1px solid #ddd;
}

.editInput {
  font-size: 18px;
  border: none;
  width: 400px;
}

.editInput:focus {
  outline: -webkit-focus-ring-color auto 0px;
}

.slot-btn {
  display: flex;
  justify-content: end;
  align-items: center;
}

.more {
  cursor: pointer;
}

.lemon-container__title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 0;
  padding-top: 0;
}

.lemon-wrapper--drawer-show {
  .lemon-drawer {
    // left: 1000px !important;
    // height: 600px !important;
    // top: 0 !important;
    // border-left: none;
    height: 96% !important;
    right: 0 !important;
    left: auto !important;
    transition: 0.3s;
    margin-top: 41px;
    box-shadow: 0 0 0 0 !important;
  }
}

.el-switch__label {
  margin-left: 20px;
}

.slot-group-notice {
  color: #999;
  padding: 6px 0;
  font-size: 12px;
}

.slot-group-title {
  font-size: 12px;
}

.slot-group-member {
  font-size: 12px;
  line-height: 18px;
}

.slot-group-menu span {
  display: inline-block;
  cursor: pointer;
  color: #888;
  margin: 4px 10px 0 0;
  border-bottom: 2px solid transparent;

  &:hover {
    color: #000;
    border-color: #333;
  }
}

.slot-contact-fixedtop {
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.slot-search {
  width: 100%;
  box-sizing: border-box;
  font-size: 14px;
  border: 1px solid #bbb;
  padding: 5px 10px;
}

.user-info-model {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

.user-info {
  width: 270px;
  height: 270px;
  border: 1px solid #bbb;
  border-radius: 10px;
  background: #fff;
  padding: 20px;
  position: absolute;
  top: 56px;
  left: 71px;
  z-index: 9999;

  .user-info-header {
    display: flex;
    border-bottom: 1px solid #ebebf2;
    padding-bottom: 10px;

    .user-info-avatar {
      width: 56px;
      height: 56px;
      background-image: url(../assets/head.png);
      background-size: 100%;
      color: #fff;
      font-size: 17px;
      text-align: center;
      line-height: 56px;
      border-radius: 10px;
    }

    .user-info-text {
      font-size: 20px;
      color: #333;
    }

    .user-info-account {
      font-size: 12px;
      color: #999;
    }
  }

  .user-info-footer {
    display: flex;
    flex-direction: column;
    padding: 20px;
    font-size: 14px;

    .user-info-label {
      display: inline-block;
      width: 72px;
      color: #999;
      line-height: 32px;
    }

    .user-info-value {
      color: #333;
    }
  }
}
</style>